<script>
import { UpdateGroupWeight, GetGroupInfo } from '@/api/api'
export default {
  name: 'GroupWeightSetting',
  data() {
    return {
      weightList: [{
        id: 1,
        name: '教练组',

        weight: 0
      },
      {
        id: 2,
        name: '自助-有限',
        weight: 0
      },
      {
        id: 3,
        name: '自助-无限',
        weight: 0
      },
      {
        id: 4,
        name: '等待组',
        weight: 0
      }]
    }
  },
  mounted() {
    this.getHomeGroupInfo()
  },
  methods: {

    clickOnSave() {
      // TODO: Validate??
      let existValue = false
      this.weightList.forEach(item => {
        if (item.weight > 0) {
          existValue = true
        }
      })
      if (!existValue) {
        this.$message.warning('请至少设置一个权重')
        return
      }

      this.requestSave()
    },
    async requestSave() {
      try {
        const params = this.weightList.map(item => {
          return {
            id: item.id,
            weight: item.weight
          }
        })
        const response = await UpdateGroupWeight(params)
        if (!response) {
          this.$message('请求出错')
          return
        }
        const { code, msg } = response.data
        if (code !== 200) {
          this.$message.error('请求出错' + msg)
          return
        }
        this.$message.success('保存成功')
      } catch (error) {
        console.error(error)
      }
    },
    async getHomeGroupInfo() {
      try {
        const response = await GetGroupInfo()
        if (!response) {
          this.$message.error('请求出错')
          return
        }
        const { data, status } = response
        if (status !== 200) {
          this.$message.error('请求出错')
          return
        }
        const { rows } = data
        this.weightList = rows.map(item => {
          return {
            id: item.id,
            name: item.groupName,
            weight: item.weight
          }
        })
        // console.log('response', response)
      } catch (error) {
        console.error(error)
      }
    }
  }
}
</script>

<template>

  <div class="group-weight-setting">

    <h4>用户分组权重设置</h4>

    <el-row style="margin-bottom:10px;">
      <el-col :span="6">
        <span style="font-weight:bold;">组别</span>
      </el-col>
      <el-col :span="18">
        <span style="font-weight:bold;">权重</span>
      </el-col>
    </el-row>

    <el-row v-for="item in weightList" :key="item.id" style="margin-bottom:10px;">
      <el-col :span="6">
        <span>{{ item.name }}</span>
      </el-col>
      <el-col :span="18">
        <el-input-number v-model="item.weight" :min="0" :max="9999" />
      </el-col>
    </el-row>

    <div class="bottom-btn">
      <el-button type="primary" @click="clickOnSave">保存</el-button>
    </div>

  </div>
</template>

<style lang="scss" scoped></style>
